<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>输入框搜索处理返回结果demo</title>
</head>

<body>
  <div>
    <input type="text" placeholder="请输入" id="ipt">
    <input type="button" value="搜索" onclick="searchFn()">
  </div>
  <div id="container"></div>
</body>
<script>
  let t1 = new Date().getTime();
  function searchFn() {
    let ipt = document.querySelector("#ipt")
    fetchDataByXhr(ipt.value);
    // fetchDataByTimeout(ipt.value);
  }

  function fetchDataByXhr(val) {
    let t2 = new Date().getTime();
    let ipt = document.querySelector("#ipt")
    // ./server2.js
    let xhr = new XMLHttpRequest();
    xhr.open('GET', `http://localhost:3000/getData?value=${val}`);
    xhr.send(null)
    xhr.onreadystatechange = function (res) {
      if (xhr.status == 200 && xhr.readyState == 4) {
        console.log(JSON.parse(xhr.responseText), t2 >= t1);
        let { data } = JSON.parse(xhr.responseText) || {};
        if (t2 >= t1) {
          t1 = new Date().getTime();
          document.querySelector('#container').innerHTML = data;
        }
      }
    }
  }

  async function fetchDataByTimeout(val) {
    let t2 = new Date().getTime();
    await sleep(val === '1' ? 10000 : 2000);
    console.log(val, t2 >= t1);
    if (t2 >= t1) {
      t1 = new Date().getTime();
      document.querySelector('#container').innerHTML = val;
    }
  }

  function sleep(ts) {
    return new Promise(resolve => setTimeout(resolve, ts))
  }

</script>

</html>